package com.http;

import android.os.Handler;
import android.os.Message;

import com.http.client.DownFileManager;
import com.http.method.FileRequest;
import com.http.method.HttpUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;

/**
 * Created by mac_wk on 14-12-10.
 */
//实现文件下载功能
public class FileThread implements Runnable {
    private FileRequest fileRequest;
    private HttpURLConnection httpURLConnection;
    private Handler handler;
    public FileThread(FileRequest fileRequest,HttpURLConnection httpURLConnection,Handler handler)
    {
        this.fileRequest = fileRequest;
        this.httpURLConnection = httpURLConnection;
        this.handler = handler;
    }

    public FileRequest getFileRequest() {
        return fileRequest;
    }

    @Override
    public void run() {
        File file = fileRequest.getFile();
        RandomAccessFile randomAccessFile = null;
        long start = fileRequest.getStart();
        long end = fileRequest.getEnd();
        InputStream inputStream = null;
        try {
            inputStream = httpURLConnection.getInputStream();
            randomAccessFile = new RandomAccessFile(file,"rws");
            randomAccessFile.seek(start);
            byte[] buffer = new byte[1024*10];
            int count = 0;
            while ((count=inputStream.read(buffer))!=-1){
                if (fileRequest.isPause())
                {
                    wait();
                }
                randomAccessFile.write(buffer,0,count);
                Message message = handler.obtainMessage(DownFileManager.DOWNFILE);
                message.arg1 = count;
                message.sendToTarget();
                start+=count;

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            httpURLConnection.disconnect();
        }
    }
}
